package com.drop.dao.impl;

import com.drop.dao.CartDao;
import com.drop.entity.Cart;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by 陈东一 on 2017/9/23 16:45
 */
@Repository
public class CartDaoImpl implements CartDao {
	private Log log = LogFactory.getLog(this.getClass());

	private SessionFactory sessionFactory;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Session getSession(){
		return sessionFactory.getCurrentSession();
	}

	@Override
	public Cart getCartByUserAndItem(int userId, int itemId) {
		String hql = "from com.drop.entity.Cart c where c.user.userId = ? and c.goods.goodsId = ?";
		return (Cart) getSession().createQuery(hql).setParameter(0,userId).setParameter(1,itemId).uniqueResult();
	}

	@Override
	public Boolean addCart(int userId, int itemId, int num) {
		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		System.out.println("当前时间：" + sdf.format(d));
		String sql = "INSERT INTO `cart` (userId,goodsId,quantity,addTime,totalPrice)  VALUES ('"+userId+"','"+itemId+"','"+num+"','"+sdf.format(d)+"','"+0+"') ; ";
		log.info(sql);
		return getSession().createSQLQuery(sql).executeUpdate() > 0 ;
	}

}
